<?php

namespace app\admin\controller\jeek;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;
/**
 * 分类管理
 *
 * @icon fa fa-circle-o
 */
class Category extends Backend
{

    /**
     * Category模型对象
     * @var \app\common\model\jeek\Category
     */
    protected $model = null;
    protected $dataLimit = 'personal'; //这个属性在基类已经定义，默认为false，表示不启用，$dataLimit可使用auth和personal两个值
    protected $dataLimitField = 'admin_id';
    
/**
 * 数据限制开启时自动填充限制字段值
 */
protected $dataLimitFieldAutoFill = true;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\jeek\Category;
        $this->view->assign("flagList", $this->model->getFlagList());
        $this->view->assign("statusList", $this->model->getStatusList());

        $ptypeList = $this->model::getTypeList();
        $this->view->assign("ptypeList", $ptypeList);


        $tree = Tree::instance();
        $tree->init(collection($this->model->order('weigh desc,id desc')->select())->toArray(), 'pid');
        $this->categorylist = $tree->getTreeList($tree->getTreeArray(0), 'name');
        $categorydata = [0 => ['type' => 'all', 'name' => __('None')]];
        foreach ($this->categorylist as $k => $v) {
            $categorydata[$v['id']] = $v;
        }

        $this->view->assign("parentList", $categorydata);
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

     public function index()
     {
         // 当前是否为关联查询
         $this->relationSearch = false;
         // 设置过滤方法
         $this->request->filter(['strip_tags', 'trim']);
         
         // 获取当前分销商已隐藏的分类ID
         $hiddenIds = Db::name('jeek_category_hide')
             ->where('admin_id', $this->auth->id)
             ->column('category_id');
     
         // 重构分类过滤逻辑
         $filteredList = [];
         foreach ($this->categorylist as $v) {
             // 平台数据且未被隐藏，或分销商自己创建的数据
            //  if (($v['admin_id'] == 1 && !in_array($v['id'], $hiddenIds)) 
            if ($v['admin_id'] == 1 || $v['admin_id'] == $this->auth->id) {
                 // 添加隐藏状态标识
                 $v['is_hidden'] = in_array($v['id'], $hiddenIds) ? 1 : 0;
                 $filteredList[] = $v;
             }
         }
     
         if ($this->request->isAjax()) {
             // 如果发送的来源是Selectpage，则转发到Selectpage
             if ($this->request->request('keyField')) {
                 return $this->selectpage();
             }
             $search = $this->request->request("search");
             $type = $this->request->request("type");
     
             // 构造父类select列表选项数据
             $list = [];
     
             foreach ($filteredList as $k => $v) { // 使用filteredList而不是categorylist
                 if ($search) {
                     if ($v['type'] == $type && (stripos($v['name'], $search) !== false || stripos($v['nickname'], $search) !== false)) {
                         if ($type == "all" || $type == null) {
                             $list = $filteredList;
                         } else {
                             $list[] = $v;
                         }
                     }
                 } else {
                     if ($type == "all" || $type == null) {
                         $list = $filteredList;
                     } elseif ($v['type'] == $type) {
                         $list[] = $v;
                     }
                 }
             }
     
             $total = count($list);
             $result = ["total" => $total, "rows" => $list];
             return json($result);
         }
         return $this->view->fetch();
     }
        /**
        * 修改
        */

     public function del($ids = "")
{
    if ($ids) {
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();
        $count = 0;
        foreach ($list as $k => $v) {
            $count += $v->delete();
        }
        if ($count) {
            $this->success();
        } else {
            $this->error(__('No rows were deleted'));
        }
    }
    $this->error(__('Parameter %s can not be empty', 'ids'));
}
     /**
      * 切换隐藏状态
      */
     public function toggle_hide()
     {
         $categoryId = $this->request->post('id');
         $adminId = $this->auth->id;
     
         // 验证是否为平台分类
         $category = $this->model->where('id', $categoryId)
             ->where('admin_id', 1)
             ->find();
         if (!$category) {
             $this->error(__('Invalid parameters'));
         }
     
         // 判断当前隐藏状态
         $exists = Db::name('jeek_category_hide')
             ->where('admin_id', $adminId)
             ->where('category_id', $categoryId)
             ->count();
     
         if ($exists) {
             // 取消隐藏
             Db::name('jeek_category_hide')
                 ->where('admin_id', $adminId)
                 ->where('category_id', $categoryId)
                 ->delete();
         } else {
             // 添加隐藏
             Db::name('jeek_category_hide')->insert([
                 'admin_id' => $adminId,
                 'category_id' => $categoryId
             ]);
         }
     
         $this->success();
     }
     
     public function batch_hide()
     {
         $ids = $this->request->post('ids/a');
        //  dump($ids);die();
         $adminId = $this->auth->id;
         
         // 获取有效的平台分类ID
         $validIds = $this->model->where('admin_id', 1)
             ->whereIn('id', $ids)
             ->column('id');
     
         $data = [];
         foreach ($validIds as $id) {
             $data[] = ['admin_id' => $adminId, 'category_id' => $id];
         }
         
         Db::name('jeek_category_hide')->insertAll($data);
         $this->success();
     }
     
     public function batch_show()
     {
         $ids = $this->request->post('ids/a');
         $adminId = $this->auth->id;
         
         Db::name('jeek_category_hide')
             ->where('admin_id', $adminId)
             ->whereIn('category_id', $ids)
             ->delete();
             
         $this->success();
     }
}
